/**
 * title: Form and Table data binding
 * desc: useAntdTable returns a search object after receiving a form instance.
 *
 * title.zh-CN: Form 与 Table 联动
 * desc.zh-CN: useAntdTable 接收 form 实例后，会返回 search 对象。
 */
/* eslint-disable react-hooks/exhaustive-deps */

import React, { useState, useEffect } from 'react';

import { Form, Input, Table, Select, Space, Button, Modal, Checkbox, Card, Tag, Spin, message } from 'antd';
import { useBoolean } from 'ahooks';
import { If } from 'babel-plugin-jsx-control-statements';
import RequestApi from '../../../utils/request';
import css from './index.scss';
/**
 * 停车用户管理
 */
export default () => {
	const [form] = Form.useForm();
	const [addForm] = Form.useForm();
	const [isModalVisible, setIsModalVisible] = useState(false);
	const [loading] = useBoolean(false);
	const [data, setData] = useState(); // 存放表格数据
	const [orgData, setOrgData] = useState(); // 存放单位信息
	const onFinish = (values) => {
		if (values.districtName === undefined) {
			values.districtName = null;
		}
		if (values.orgName === undefined) {
			values.orgName = null;
		}
		if (values.realName === undefined) {
			values.realName = null;
		}
		if (values.roles === undefined) {
			values.roles = null;
		}
		if (values.type === undefined) {
			values.type = null;
		}
		if (values.username === undefined) {
			values.username = null;
		}
		RequestApi.connection('post', `user/getManageUser`, values).then((res) => {
			setData(res.data);
		}, []);
	};

	const onFinishFailed = (errorInfo) => {
		console.log('Failed:', errorInfo);
	};
	// 通过区域名字提取到districtId
	const [districtListState, setDistrictListState] = useState();
	useEffect(() => {
		RequestApi.connection('get', `district/getList`).then((res) => {
			setDistrictListState(res.data);
		});
	}, []);
	const districtList = [];
	if (districtListState !== undefined && districtListState !== null) {
		districtListState.map((item) => {
			const district = {};
			district.id = item.id;
			district.districtName = item.name;
			districtList.push(district);
			if (item.sonArea !== null) {
				item.sonArea.map((sonAreaItem) => {
					const newDistrict = {};
					newDistrict.id = sonAreaItem.id;
					newDistrict.districtName = sonAreaItem.name;
					districtList.push(newDistrict);
					return null;
				});
			}
			return null;
		});
		const cqDistrict = {};
		cqDistrict.id = 1;
		cqDistrict.districtName = '重庆市';
		districtList.push(cqDistrict);
	}

	// 获取表格的信息，参数默认为空
	useEffect(() => {
		RequestApi.connection('post', `user/getManageUser`).then((res) => {
			setData(res.data);
		});
	}, []);

	// 获取单位信息
	useEffect(() => {
		RequestApi.connection('post', `orgnization/getOrgList`).then((res) => {
			setOrgData(res.data);
		});
	}, []);

	const reset = () => {
		form.setFieldsValue({
			districtName: null,
			orgName: null,
			realName: null,
			username: null,
			roles: null,
			type: null,
		});
		RequestApi.connection('post', `user/getManageUser`).then((res) => {
			setData(res.data);
		});
	};
	const addUser = () => {
		setIsModalVisible(true);
	};

	// 处理获取添加用户表单的信息
	const onFinishAddForm = (values) => {
		if (districtList !== null && districtList !== undefined) {
			districtList.map((item) => {
				if (item.districtName === values.districtName) {
					values.districtId = item.id;
				}
				return null;
			});
		}
		if (orgData !== null && orgData !== undefined) {
			orgData.map((orgItem) => {
				if (orgItem.name === values.orgName) {
					values.orgId = orgItem.id;
				}
				return null;
			});
		}
		// values.roles是列表，将列表转化为字符串
		let strRole = '';
		if (values.roles !== null && values.roles !== undefined) {
			values.roles.map((item) => {
				strRole += item;
				strRole += ',';
				return null;
			});
			values.roles = strRole;
		}
		values.roles = strRole;
		// console.log('values:', values);
		RequestApi.connection('post', `user/add`, values).then(() => {
			message.success('添加成功');
		});
	};

	const handleCancel = () => {
		setIsModalVisible(false);
		addForm.setFieldsValue({
			address: null,
			contact: null,
			districtId: null,
			districtName: null,
			name: null,
			parentOrgId: null,
			parentOrgName: null,
			remark: null,
			tel: null,
		});
	};

	// 多选框选项
	const rolesOptions = [
		{ label: '初审', value: '初审' },
		{ label: '勘察员', value: '勘察员' },
		{ label: '领导', value: '领导' },
		{ label: '区县管理员', value: '区县管理员' },
		{ label: '市管理员', value: '市管理员' },
	];
	const [roles, setRoles] = useState();
	const rolesOnChange = (checkedValues) => {
		// console.log('checked = ', checkedValues);
		setRoles(checkedValues);
	};
	const tagOnClose = (value) => {
		console.log('value: ', value);
		const newTags = [];
		for (let i = 0; i < roles.length - 1; i += 1) {
			if (roles[i] !== value) {
				newTags.push(roles[i]);
			}
		}
		setRoles(newTags);
		addForm.setFieldsValue({
			roles: newTags,
		});
	};

	// 状态改变
	const statusChange = (status, userId) => {
		// console.log(status, userId);
		if (status === 1) {
			status = 0;
		} else {
			status = 1;
		}
		RequestApi.connection('get', `user/updateUserStatus/${userId}/${status}`)
			.then(() => {
				RequestApi.connection('post', `user/getManageUser`).then((res) => {
					setData(res.data);
				});
				message.success('修改状态成功');
			})
			.catch(() => {
				message.error('修改状态失败！！');
			});
	};
	const columns = [
		{
			title: '功能列',
			dataIndex: '',
			render: (record) => {
				return (
					<Space>
						<Button type="link" value="small">
							编辑
						</Button>
						<Button type="link" style={{ marginLeft: -20 }} value="small">
							查看
						</Button>

						<If condition={record.status === 1}>
							<Button
								type="link"
								onClick={() => statusChange(record.status, record.id)}
								value="small"
								style={{ color: 'red', marginLeft: -22 }}
							>
								禁用
							</Button>
						</If>
						<If condition={record.status === 0}>
							<Button
								type="link"
								onClick={() => statusChange(record.status, record.id)}
								value="small"
								style={{ marginLeft: -22 }}
							>
								启用
							</Button>
						</If>
					</Space>
				);
			},
		},
		{
			title: '行政区域',
			dataIndex: 'districtName',
		},
		{
			title: '所属单位名称',
			dataIndex: 'orgName',
		},
		{
			title: '状态',
			dataIndex: 'status',
			render: (text) => {
				return (
					<Space>
						<If condition={text === 0}>
							<p>禁用</p>
						</If>
						<If condition={text === 1}>
							<p>启用</p>
						</If>
					</Space>
				);
			},
		},
		{
			title: '姓名',
			dataIndex: 'realName',
		},
		{
			title: '用户名',
			dataIndex: 'id',
			render: (text) => {
				return (
					<>
						{data.map((item) => (
							<If condition={item.id === text}>
								<p>{item.username}</p>
							</If>
						))}
					</>
				);
			},
		},
		{
			title: '联系电话',
			dataIndex: 'mobile',
		},
		{
			title: '角色',
			dataIndex: 'roles',
			render: (text) => (
				<>
					<If condition={text !== null}>
						{text.split(',').map((tag, index) => {
							const color = index % 2 === 0 ? 'green' : 'geekblue';
							return (
								<If condition={tag !== ''}>
									<Tag color={color} key={tag} size="small">
										{tag}
									</Tag>
								</If>
							);
						})}
					</If>
				</>
			),
		},
		{
			title: '备注',
			dataIndex: 'remark',
		},
	];

	return (
		<>
			<Form
				form={form}
				className={css.table_list_form}
				layout="inline"
				onFinish={onFinish}
				onFinishFailed={onFinishFailed}
				labelCol={{ span: 10 }}
				// width={1200}
			>
				<Form.Item name="districtName" label="区域 " className={css.item}>
					<Select style={{ width: 300 }} placeholder="请选择区域" allowClear>
						<If condition={districtList !== null && districtList !== undefined}>
							{districtList.map((item) => (
								<Select.Option value={item.districtName} key={item.id}>
									{item.districtName}
								</Select.Option>
							))}
						</If>
					</Select>
				</Form.Item>
				<Form.Item name="orgName" label="单位名称：" className={css.item}>
					<Input placeholder="请输入单位名称关键字" style={{ width: 300 }} allowClear />
				</Form.Item>
				<Form.Item name="realName" label="用户姓名：" className={css.item}>
					<Input placeholder="请输入用户姓名" style={{ width: 300 }} allowClear />
				</Form.Item>
				<Form.Item name="username" label="用户名：" className={css.item}>
					<Input placeholder="请输入用户账号" style={{ width: 300 }} allowClear />
				</Form.Item>

				<Form.Item name="roles" label="角色 " className={css.item}>
					<Select style={{ width: 340 }} placeholder="请选择角色">
						<Select.Option value="资料初审">资料初审</Select.Option>
						<Select.Option value="现场勘查">现场勘查</Select.Option>
						<Select.Option value="领导">领导</Select.Option>
						<Select.Option value="区县管理员">区县管理员</Select.Option>
						<Select.Option value="市管理员">市管理员</Select.Option>
						<Select.Option value="经营业主">经营业主</Select.Option>
					</Select>
				</Form.Item>
				<Form.Item name="type" label="单位类型 " className={css.item}>
					<Select style={{ width: 300 }} placeholder="请选择单位类型">
						<Select.Option value="0">停车单位</Select.Option>
						<Select.Option value="1">停车管理单位</Select.Option>
						<Select.Option value="2">勘查人员单位</Select.Option>
						<Select.Option value="3">经营业主单位</Select.Option>
					</Select>
				</Form.Item>
				<Space>
					<div className={css.button}>
						<Button type="primary" htmlType="submit">
							查询
						</Button>
						<Button onClick={reset}>重置</Button>
						<Button type="primary" style={{ marginLeft: 492 }} onClick={addUser}>
							新增用户
						</Button>
						<Modal visible={isModalVisible} onCancel={handleCancel} width={700} footer={[]}>
							{/* form={form} 有问题，到时候再改 */}
							<Form
								name="addCompany"
								form={addForm}
								onFinish={onFinishAddForm}
								labelCol={{ span: 3 }}
								style={{ marginTop: 20 }}
							>
								<h2>
									<strong>账号信息</strong>
								</h2>
								<Form.Item label="用户名:" name="username" rules={[{ required: true, message: '用户名不能为空' }]}>
									<Input type="text" placeholder="请填写用户名" />
								</Form.Item>
								<Form.Item label="密码:" name="password" rules={[{ required: true, message: '密码不能为空' }]}>
									<Input type="password" placeholder="请填写密码" />
								</Form.Item>
								<h2>
									<strong>用户信息</strong>
								</h2>
								<Form.Item label="区域:" name="districtName" rules={[{ required: true, message: '区域不能为空' }]}>
									<Select placeholder="请选择区域" filterOption={false} showSearch allowClear>
										<If condition={districtList !== null && districtList !== undefined}>
											{districtList.map((item) => (
												<Select.Option value={item.districtName} key={item.id}>
													{item.districtName}
												</Select.Option>
											))}
										</If>
									</Select>
								</Form.Item>
								<Form.Item label="单位:" name="orgName" rules={[{ required: true, message: '单位不能为空' }]}>
									<Select placeholder="请选择单位" filterOption={false} showSearch>
										<If condition={orgData !== null && orgData !== undefined}>
											{orgData.map((item) => (
												<Select.Option value={item.name} key={item.id}>
													{item.name}
												</Select.Option>
											))}
										</If>
									</Select>
								</Form.Item>
								<Form.Item label="用户姓名:" name="realName" rules={[{ required: true, message: '单位不能为空' }]}>
									<Input placeholder="请填写用户联系姓名" />
								</Form.Item>
								<Form.Item
									validateTrigger="onBlur"
									label="联系电话:"
									name="mobile"
									rules={[{ required: true, message: '联系电话不能为空' }]}
								>
									<Input placeholder="请填写用户联系电话" />
								</Form.Item>
								<Form.Item validateTrigger="onBlur" label="办公室电话:" name="orgTel">
									<Input placeholder="请填写办公室联系电话" />
								</Form.Item>
								<Form.Item label="所属角色:" rules={[{ required: true, message: '角色不能为空' }]}>
									<Card>
										<If condition={roles !== undefined && roles !== null}>
											{roles.map((item) => (
												<Tag
													key={item}
													closable
													onClose={() => {
														tagOnClose(item);
													}}
												>
													{item}
												</Tag>
											))}
										</If>
										<Form.Item name="roles">
											<Checkbox.Group options={rolesOptions} onChange={rolesOnChange} />
										</Form.Item>
									</Card>
								</Form.Item>
								<Form.Item label="备注:" name="remark">
									<Input.TextArea showCount maxLength={500} rows={4} placeholder="请填写备注" />
								</Form.Item>
								<Space>
									<Button type="primary" htmlType="submit" style={{ marginLeft: 80 }} onClick={onFinishAddForm}>
										保存
									</Button>
									<Button onClick={handleCancel} style={{ marginLeft: 40 }}>
										返回
									</Button>
								</Space>
							</Form>
						</Modal>
					</div>
				</Space>
			</Form>
			<Spin spinning={loading} tip="加载中...">
				<Table
					size="small"
					bordered
					columns={columns}
					scroll={{ y: 'calc(100vh - 290px)' }}
					rowKey="email"
					dataSource={data}
				/>
			</Spin>
		</>
	);
};
